package com.jourwon.spring.boot.config;

import com.jourwon.spring.boot.constant.SystemConstants;
import com.jourwon.spring.boot.util.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * TraceId过滤器配置
 *
 * @author JourWon
 * @date 2022/6/26
 */
@Configuration
public class TraceIdFilterConfig implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 设置traceId(链路id)，如果请求头有traceId就用请求头的traceId，没有的话就新生成一个traceId
        String traceId = request.getHeader(SystemConstants.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = UuidUtils.generateShortUuid();
        }
        MDC.put(SystemConstants.TRACE_ID, traceId);

        filterChain.doFilter(servletRequest, servletResponse);

        // 处理完请求，清除MDC里面的traceId
        if (StringUtils.isNotBlank(MDC.get(SystemConstants.TRACE_ID))) {
            MDC.remove(SystemConstants.TRACE_ID);
        }
    }

}
